package com.tuzhi.sys.scurity;

import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.security.service.impl.TokenServiceImpl;
import com.tuzhi.security.service.impl.UserServiceImpl;
import com.tuzhi.sys.jpa.entity.SysMenuEntity;
import com.tuzhi.sys.jpa.entity.SysUserEntity;
import com.tuzhi.sys.service.SysMenuService;
import com.tuzhi.sys.service.SysRoleMenuService;
import com.tuzhi.sys.service.SysUserRoleService;
import com.tuzhi.sys.service.SysUserService;
import com.tuzhi.util.StringTzUtil;
import com.tuzhi.utils.RsaEncipherUtil;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.regex.Pattern;

@Primary
@Service
public class MyUserServiceImpl extends UserServiceImpl {

/*    private final String superRoleName = "admin"; //超级管理员角色名
    private final String deptMgrRoleName = "manager"; //部门管理角色名*/


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TokenServiceImpl tokenService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    RsaEncipherUtil rsaEncipherUtil;

    @Override
    public void verify(String userName, String pwd, String codeKey, String code) {
        if (StringTzUtil.isBlankNull(userName)) {
            throw new BusinessException("用户不能为空");
        }
        if (StringTzUtil.isBlankNull(pwd)) {
            throw new BusinessException("密码不能为空");
        }
        SysUserEntity entity = sysUserService.getUserByUserName(userName);
        if (entity == null) {
            log.info("{}:登录时，帐号不存在", userName);
            throw new BusinessException("帐号不存在");
        }

        if (!"clientapp".equalsIgnoreCase(codeKey)) {
            //TODO Test
//            Map<String, String> publicKeyAndPrivateKey = rsaEncipherUtil.getPublicKeyAndPrivateKey();
//            String privateKeyStr = publicKeyAndPrivateKey.get(RsaEncipherUtil.PRIVATE_KEY_STR);
//            String s = RsaEncipherUtil.decryptByPrivateKey(pwd, privateKeyStr);
//            pwd=s;
            boolean flag = BCrypt.checkpw(pwd, entity.getPassword());
            if (!flag) {
                log.info("{}:登录时，密码错误", userName);
                throw new BusinessException("登录时，密码错误");
            }
        }

        if (entity.getOrgId() == null) {
            throw new BusinessException("用户没有所属于的组织org,请先配置组orgId");
        }

        if (entity.getSysStatus().intValue() != 0) {
            throw new BusinessException(String.format("%s:当前用户状态非正常状态，请联系管理员", entity.getId()));
        }

        //super.verify(userName, pwd, codeKey, code);
    }

//    @Override
    public Map<String,String> verifyMobile(String pwd, String phone, String codeKey) {
        if (StringTzUtil.isBlankNull(phone)) {
            throw new BusinessException("手机号不能为空");
        }
        if (StringTzUtil.isBlankNull(pwd)) {
            throw new BusinessException("密码不能为空");
        }
        String regex = "^1[3-9]\\d{9}$";
        if (Pattern.matches(regex, phone) == false){
            throw new BusinessException("手机号格式不正确");
        }
        SysUserEntity entity = sysUserService.getUserByMobile(phone);
        if (entity == null) {
            log.info("{}:登录时，手机号不存在", phone);
            throw new BusinessException("帐号不存在");
        }

        if (!"clientapp".equalsIgnoreCase(codeKey)) {
            boolean flag = BCrypt.checkpw(pwd, entity.getPassword());
            if (!flag) {
                log.info("{}:登录时，密码错误", entity.getUsername());
                throw new BusinessException("登录时，密码错误");
            }
        }

        if (entity.getOrgId() == null) {
            throw new BusinessException("用户没有所属于的组织org,请先配置组orgId");
        }

        if (entity.getSysStatus().intValue() != 0) {
            throw new BusinessException(String.format("%s:当前用户状态非正常状态，请联系管理员", entity.getId()));
        }

        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("userName", entity.getUsername());
        return resultMap;
    }

    @Override
    public LoginUserBO createLoginUser(String userId, String pwd) {
        LoginUserBO loginUserBO = super.createLoginUser(userId, pwd);
        SysUserEntity entity = sysUserService.getUserByUserName(userId);
        loginUserBO.setUserId(entity.getId());
        loginUserBO.setDeptId(entity.getOrgId());
        loginUserBO.setOrgId(entity.getOrgId());
        loginUserBO.setNickName(entity.getNickname());
        loginUserBO.setTel(entity.getPhone());
       /* List<SysRoleEntity> roles = sysUserService.listRoles4UserName(userId);
        if (roles != null && !roles.isEmpty()) {
            Set<String> roleNameSet = roles.stream().map(SysRoleEntity::getName).collect(Collectors.toSet());
            if (roleNameSet.contains(this.superRoleName)) {
                loginUserBO.setSupper(true);
            }
            if (roleNameSet.contains(this.deptMgrRoleName)) {
                loginUserBO.setDeptMgr(true);
            }
            loginUserBO.setRoles(roleNameSet);
        }*/
        return loginUserBO;
    }

    @Override
    public void setData(LoginUserBO loginUserBO) {
//        loginUserBO.setPermissions(getPermissions4User(loginUserBO.getUserName()));
        String token = tokenService.createToken(loginUserBO);
        loginUserBO.setToken(token);
        //super.setData(loginUserBO);
    }


    /**
     * 获取指定用户所具有的所有权限集合
     *
     * @param userName
     * @return
     */
    private Set<String> getPermissions4User(String userName) {
        Set<String> permissions = new HashSet<>();
        SysUserEntity sysUserEntity = sysUserService.getUserByUserName(userName);
        if (sysUserEntity == null) {
            return permissions;
        }

        List<Long> roleIds = sysUserRoleService.listRoleId4UserId(sysUserEntity.getId());
        if (roleIds == null || roleIds.isEmpty()) {
            return permissions;
        }

        List<Long> menuIds;
        for (Long roleId : roleIds) {
            menuIds = sysRoleMenuService.listMenuId4Role(roleId);
            for (Long mid : menuIds) {
                SysMenuEntity sysMenuEntity = sysMenuService.findById(mid);
                if (sysMenuEntity != null) {
                    permissions.add(sysMenuEntity.getPerms());
                }
            }
        }

        return permissions;
    }

}
